<!-- 车间管理 -->
<template>
  <div class="workshop-management">
    <div class="title-section">
      <h2>车间管理</h2>
      <button class="btn-primary" @click="showAddDialog">新建</button>
    </div>

    <div class="controls-section">
      <div class="filters">
        <div class="filter-item">
          <label>车间编号</label>
          <input type="text" v-model="searchForm.workshopCode" placeholder="请输入车间编号">
        </div>
        <div class="filter-item">
          <label>车间名称</label>
          <input type="text" v-model="searchForm.workshopName" placeholder="请输入车间名称">
        </div>
        <div class="filter-item">
          <label>负责人</label>
          <input type="text" v-model="searchForm.username" placeholder="请输入负责人">
        </div>
        <div class="filter-item">
          <label>状态</label>
          <select v-model="searchForm.status">
            <option value="">全部</option>
            <option value="0">启用</option>
            <option value="1">停用</option>
          </select>
        </div>
      </div>
      <div class="actions">
        <button class="btn-primary" @click="searchWorkshops">搜索</button>
        <button class="btn-secondary" @click="resetSearch">重置</button>
      </div>
    </div>

    <div class="table-section">
      <table>
        <thead>
        <tr>
          <th><input type="checkbox" v-model="selectAll" @change="toggleSelectAll"></th>
          <th>车间编号</th>
          <th>车间名称</th>
          <th>车间负责人</th>
          <th>状态</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(row, index) in tableData" :key="row.id || index">
          <td><input type="checkbox" v-model="row.selected" @change="updateSelectAll"></td>
          <td class="link-style" @click="viewWorkshop(row)">{{ row.workshopCode }}</td>
          <td>{{ row.workshopName }}</td>
          <td>{{ row.username}}</td>
          <td>
            <span :class="row.status === 0 ? 'status-active' : 'status-inactive'">
              {{ row.status === 0 ? '启用' : '禁用' }}
            </span>
          </td>
          <td>
            <button class="btn-link" @click="editWorkshop(row)">编辑</button>
            <button class="btn-link btn-danger" @click="deleteWorkshop(row.id)">删除</button>
          </td>
        </tr>
        </tbody>
      </table>
    </div>

    <div class="footer-section">
      <div class="footer-left">
        <input type="checkbox" v-model="selectAll" @change="toggleSelectAll">
        <label>全选</label>
        <button class="btn-secondary" @click="batchDelete" :disabled="!hasSelected">批量删除</button>
        <button class="btn-secondary" @click="exportData">导出</button>
      </div>
      <div class="pagination">
        <button @click="prevPage" :disabled="currentPage === 1">&lt;</button>
        <button v-for="page in totalPages" :key="page" :class="{ active: currentPage === page }" @click="goToPage(page)">{{ page }}</button>
        <button @click="nextPage" :disabled="currentPage === totalPages">&gt;</button>
        <select v-model="pageSize" @change="handlePageSizeChange">
          <option value="10">10条/页</option>
          <option value="20">20条/页</option>
          <option value="50">50条/页</option>
        </select>
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <div v-if="showDialog" class="dialog-overlay" @click="closeDialog">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h3>{{ isEdit ? '编辑车间' : '新增车间' }}</h3>
          <button class="btn-close" @click="closeDialog">&times;</button>
        </div>
        <div class="dialog-body">
          <form @submit.prevent="submitForm">
            <div class="form-row">
              <div class="form-item">
                <label>车间编号</label>
                <input type="text" v-model="form.workshopCode" placeholder="可不填,后端自动生成">
              </div>
              <div class="form-item">
                <label>车间名称 <span class="required">*</span></label>
                <input type="text" v-model="form.workshopName" placeholder="请输入车间名称" required>
              </div>
            </div>
            <div class="form-row">
              <div class="form-item">
                <label>负责人 <span class="required">*</span></label>
                <input type="text" v-model="form.username" placeholder="请输入负责人" required>
              </div>
              <div class="form-item">
                <label>状态 <span class="required">*</span></label>
                <select v-model="form.status" required>
                  <option value="0">启用</option>
                  <option value="1">禁用</option>
                </select>
              </div>
            </div>
            <div class="form-actions">
              <button type="button" class="btn-secondary" @click="closeDialog">取消</button>
              <button type="submit" class="btn-primary">{{ isEdit ? '更新' : '保存' }}</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 详情弹窗 -->
    <div v-if="showDetail" class="dialog-overlay" @click="showDetail = false">
      <div class="dialog-content detail-dialog" @click.stop>
        <div class="dialog-header">
          <h3>车间详情</h3>
          <button class="btn-close" @click="showDetail = false">&times;</button>
        </div>
        <div class="dialog-body">
          <div class="detail-content">
            <div class="detail-row">
              <div class="detail-label">车间编号:</div>
              <div class="detail-value">{{ detailData.workshopCode || '无数据' }}</div>
            </div>
            <div class="detail-row">
              <div class="detail-label">车间名称:</div>
              <div class="detail-value">{{ detailData.workshopName || '无数据' }}</div>
            </div>
            <div class="detail-row">
              <div class="detail-label">负责人:</div>
              <div class="detail-value">{{ detailData.username || '无数据' }}</div>
            </div>
            <div class="detail-row">
              <div class="detail-label">状态:</div>
              <div class="detail-value">
                <span :class="detailData.status === 0 ? 'status-active' : 'status-inactive'">
                  {{ detailData.status === 0 ? '启用' : '禁用' }}
                </span>
              </div>
            </div>
          </div>
          <div class="form-actions">
            <button type="button" class="btn-secondary" @click="showDetail = false">关闭</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { workshopApi } from '@/api/workshop'

export default {
  name: 'WorkshopManagement',
  data() {
    return {
      selectAll: false,
      currentPage: 1,
      pageSize: 10,
      totalPages: 1,
      total: 0,
      tableData: [],
      showDialog: false,
      isEdit: false,
      showDetail: false,
      detailData: {},
      searchForm: {
        workshopCode: '',
        workshopName: '',
        username: '',
        status: ''
      },
      form: {
        equipemtId: null,
        workshopCode: '',
        workshopName: '',
        username: '',
        status: 0
      }
    }
  },
  computed: {
    hasSelected() {
      return this.tableData.some(row => row.selected)
    }
  },
  mounted() {
    this.loadWorkshops()
  },
  methods: {
    // 加载车间数据
    async loadWorkshops() {
      try {
        const params = {
          current: this.currentPage,
          size: this.pageSize,
          ...this.searchForm
        }
        const response = await workshopApi.getWorkshopsPage(params)
        this.tableData = response.data.records.map(item => ({
          ...item,
          selected: false
        }))
        this.total = response.data.total
        this.totalPages = Math.ceil(this.total / this.pageSize)
      } catch (error) {
        console.error('加载车间数据失败:', error)
        this.$message.error('加载数据失败')
      }
    },

    // 搜索车间
    searchWorkshops() {
      this.currentPage = 1
      this.loadWorkshops()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        workshopCode: '',
        workshopName: '',
        username: '',
        status: ''
      }
      this.currentPage = 1
      this.loadWorkshops()
    },

    // 显示新增对话框
    showAddDialog() {
      this.isEdit = false
      this.form = {
        id: null,
        workshopCode: '',
        workshopName: '',
        username: '',
        status: 0
      }
      this.showDialog = true
    },

    // 编辑车间
    editWorkshop(row) {
      this.isEdit = true
      this.form = { ...row }
      this.showDialog = true
    },

    // 查看车间详情
    async viewWorkshop(row) {
      try {
        console.log('点击的行数据:', row)

        // 先使用表格行中的现有数据
        let workshopData = { ...row }

        // 尝试根据ID查询车间详细信息
        try {
          const response = await workshopApi.getWorkshopById(row.id)
          console.log('API响应数据:', response)

          // 检查响应数据结构
          const apiData = response.data || response
          console.log('处理后的API数据:', apiData)

          // 如果API返回了数据，则使用API数据
          if (apiData && Object.keys(apiData).length > 0) {
            workshopData = { ...apiData }
          }
        } catch (apiError) {
          console.warn('API查询失败，使用表格数据:', apiError)
        }

        console.log('最终使用的数据:', workshopData)
        // 显示车间详情弹窗
        this.showDetailDialog(workshopData)
      } catch (error) {
        console.error('查看车间详情失败:', error)
        this.$message.error('查看车间详情失败')
      }
    },

    // 显示详情弹窗
    showDetailDialog(workshop) {
      console.log('设置详情数据:', workshop)
      this.detailData = { ...workshop }
      this.showDetail = true
    },

    // 生成车间编号
    async generateCode() {
      try {
        const code = await workshopApi.generateWorkshopCode()
        this.form.workshopCode = code
      } catch (error) {
        console.error('生成编号失败:', error)
        this.$message.error('生成编号失败')
      }
    },

    // 提交表单
    async submitForm() {
      try {
        if (this.isEdit) {
          await workshopApi.updateWorkshop(this.form)
          this.$message.success('更新成功')
        } else {
          await workshopApi.addWorkshop(this.form)
          this.$message.success('添加成功')
        }
        this.closeDialog()
        this.loadWorkshops()
      } catch (error) {
        console.error('操作失败:', error)
        this.$message.error('操作失败')
      }
    },

    // 删除车间
    async deleteWorkshop(id) {
      if (!confirm('确定要删除这个车间吗？')) return

      try {
        await workshopApi.deleteWorkshopById(id)
        this.$message.success('删除成功')
        this.loadWorkshops()
      } catch (error) {
        console.error('删除失败:', error)
        this.$message.error('删除失败')
      }
    },

    // 批量删除
    async batchDelete() {
      const selectedIds = this.tableData.filter(row => row.selected).map(row => row.id)
      if (selectedIds.length === 0) {
        this.$message.warning('请选择要删除的车间')
        return
      }

      if (!confirm(`确定要删除选中的 ${selectedIds.length} 个车间吗？`)) return

      try {
        for (const id of selectedIds) {
          await workshopApi.deleteWorkshopById(id)
        }
        this.$message.success('批量删除成功')
        this.loadWorkshops()
      } catch (error) {
        console.error('批量删除失败:', error)
        this.$message.error('批量删除失败')
      }
    },

    // 导出数据
    exportData() {
      // 实现导出功能
      console.log('导出数据')
    },

    // 关闭对话框
    closeDialog() {
      this.showDialog = false
      this.form = {
        equipemtId: null,
        workshopCode: '',
        workshopName: '',
        username: '',
        status: 0
      }
    },

    // 分页相关方法
    toggleSelectAll() {
      this.tableData.forEach(row => { row.selected = this.selectAll })
    },
    updateSelectAll() {
      this.selectAll = this.tableData.every(row => row.selected)
    },
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--
        this.loadWorkshops()
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++
        this.loadWorkshops()
      }
    },
    goToPage(page) {
      this.currentPage = page
      this.loadWorkshops()
    },
    handlePageSizeChange() {
      this.currentPage = 1
      this.loadWorkshops()
    }
  }
}
</script>

<style scoped>
.workshop-management { padding: 20px; background-color: #f5f7fa; }
.title-section { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.title-section h2 { font-size: 20px; font-weight: bold; }
.controls-section { display: flex; justify-content: space-between; flex-wrap: wrap; gap: 16px; padding: 20px; background-color: #fff; border-radius: 8px; margin-bottom: 20px; align-items: center; }
.filters { display: flex; flex-wrap: wrap; gap: 16px; align-items: center; }
.filter-item { display: flex; align-items: center; gap: 8px; }
.filter-item label { font-size: 14px; white-space: nowrap; }
.filter-item input, .filter-item select { padding: 8px; border: 1px solid #dcdfe6; border-radius: 4px; width: 150px; }
.actions { display: flex; gap: 10px; }
.btn-primary { background-color: #409eff; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer; }
.btn-secondary { background-color: #fff; color: #606266; border: 1px solid #dcdfe6; padding: 8px 16px; border-radius: 4px; cursor: pointer; }
.btn-link { background: none; border: none; color: #409eff; cursor: pointer; text-decoration: underline; margin: 0 5px; }
.btn-danger { color: #f56c6c; }
.btn-close { background: none; border: none; font-size: 20px; cursor: pointer; color: #999; }
.table-section { background-color: #fff; padding: 20px; border-radius: 8px; }
table { width: 100%; border-collapse: collapse; }
th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ebeef5; }
th { background-color: #f8f9fa; }
.link-style { color: #409eff; cursor: pointer; text-decoration: underline; }
.link-style:hover { color: #66b1ff; text-decoration: none; }
.status-active { color: #67c23a; }
.status-inactive { color: #f56c6c; }
.footer-section { display: flex; justify-content: space-between; align-items: center; margin-top: 20px; background-color: #fff; padding: 10px 20px; border-radius: 8px; }
.footer-left { display: flex; align-items: center; gap: 8px; }
.pagination { display: flex; align-items: center; gap: 8px; }
.pagination button { padding: 6px 12px; border: 1px solid #dcdfe6; background-color: #fff; cursor: pointer; border-radius: 4px; }
.pagination button.active { background-color: #409eff; color: white; border-color: #409eff; }
.pagination button:disabled { opacity: 0.5; cursor: not-allowed; }
.pagination select { padding: 6px; border: 1px solid #dcdfe6; border-radius: 4px; }

/* 对话框样式 */
.dialog-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.5); display: flex; justify-content: center; align-items: center; z-index: 1000; }
.dialog-content { background-color: #fff; border-radius: 8px; width: 600px; max-width: 90vw; max-height: 90vh; overflow-y: auto; }
.dialog-header { display: flex; justify-content: space-between; align-items: center; padding: 20px; border-bottom: 1px solid #ebeef5; }
.dialog-header h3 { margin: 0; font-size: 18px; font-weight: bold; color: #000; }
.dialog-body { padding: 20px; }
.form-row { display: flex; gap: 20px; margin-bottom: 20px; }
.form-item { flex: 1; }
.form-item label { display: block; margin-bottom: 8px; font-weight: 500; color: #000; }
.form-item input, .form-item select { width: 100%; padding: 8px; border: 1px solid #dcdfe6; border-radius: 4px; box-sizing: border-box; }
.required { color: #f56c6c; margin-left: 2px; }
.form-actions { display: flex; justify-content: flex-end; gap: 12px; margin-top: 20px; padding-top: 20px; border-top: 1px solid #ebeef5; }

/* 详情弹窗样式 */
.detail-dialog { width: 500px; }
.detail-content { margin-bottom: 20px; }
.detail-row { display: flex; margin-bottom: 16px; align-items: flex-start; }
.detail-label { width: 100px; font-weight: 500; color: #606266; flex-shrink: 0; }
.detail-value { flex: 1; color: #303133; word-break: break-all; }
</style>
